package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.CurrentLoginUserUtil;
import com.gxuwz.stats.entity.AchievementTransfer;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.AchievementTransferService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/adminAchieveTransfer")
public class AchieveTransferController {
    @Autowired
    private AchievementTransferService achievementTransferService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/getAchieveTranList")
    public ResponseEntity<Map<String, Object>> getAchieveTranList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            System.out.println("sdff="+params);
            // 提取 Token
            String token = authorization.replace("Bearer ", "");

// 解析 Token 获取当前用户ID（假设使用 JWT）
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            String userId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<AchievementTransfer> page = new Page<>(currentPage, pageSize);
            QueryWrapper<AchievementTransfer> queryWrapper = new QueryWrapper<>();


// 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }
            // 模糊查询条件 - 成果名称
            if (params.containsKey("transferName") && params.get("transferName") != null && !params.get("transferName").isEmpty()) {
                queryWrapper.like("transfer_name", params.get("transferName"));
            }

            // 模糊查询条件 - 成果类别
            if (params.containsKey("transferType") && params.get("transferType") != null && !params.get("transferType").isEmpty()) {
                queryWrapper.like("transfer_type", params.get("transferType"));
            }
            // 模糊查询条件 - 获得时间
            if (params.containsKey("transferYear") && params.get("transferYear") != null && !params.get("transferYear").isEmpty()) {
                queryWrapper.apply("YEAR(transfer_year) = {0}", params.get("transferYear"));
            }

            // 模糊查询条件 - 审核状态
            if (params.containsKey("transferReviewStatus") && params.get("transferReviewStatus")!= null &&!params.get("transferReviewStatus").isEmpty()) {
                queryWrapper.eq("transfer_review_status", params.get("transferReviewStatus"));
            }

            // 查询条件 - 提交状态
            if (params.containsKey("transferStatus") && params.get("transferStatus") != null && !params.get("transferStatus").isEmpty()) {
                queryWrapper.eq("transfer_status", params.get("transferStatus"));
            }


            // 调用 service 层的分页查询方法
            IPage<AchievementTransfer> resultPage = achievementTransferService.getAchieveTransferList(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增决策咨询数据
     */
    @PostMapping("/addAchieveTrans")
    public ResponseEntity<Map<String, Object>> saveAchieveTrans(@RequestBody AchievementTransfer achievementTransfer) {
        System.out.println("前端数据：" + achievementTransfer);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();

        // 1. 验证 username 是否存在
        String username = achievementTransfer.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        achievementTransfer.setUserId(userId);
        // 4. 自动计算分值
        int baseScore = achievementTransferService.calculateTransferScore(achievementTransfer.getTransferType(), achievementTransfer.getTransferAmount());
        achievementTransfer.setTransferScore(baseScore);

        achievementTransfer.setTransferSubmissionTime(LocalDateTime.now());
        achievementTransfer.setTransferStatus("已提交");
        achievementTransfer.setTransferReviewStatus("未审核");
        try {
            // 保存到数据库
            achievementTransferService.save(achievementTransfer);

            //总分值
            String year = null;
            if (achievementTransfer.getTransferYear() != null) {
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    year = new SimpleDateFormat("yyyy").format(sdf.parse(achievementTransfer.getTransferYear()));
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = achievementTransfer.getTransferYear().substring(0, 4);
                }
            }
            if (year != null) {
                achievementTransferService.updateTotalWorkTransferScore(userId, year);
            }

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/updateAchieveTrans")
    public ResponseEntity<Map<String, Object>> updateAchieveTrans(
            @RequestBody AchievementTransfer achievementTransfer
    ) {
        // 1. 获取前端传递的用户名
        String username = achievementTransfer.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            achievementTransfer.setUserId(user.getUserId());
        }

        // 4. 自动计算分值
        int baseScore = achievementTransferService.calculateTransferScore(achievementTransfer.getTransferType(), achievementTransfer.getTransferAmount());
        achievementTransfer.setTransferScore(baseScore);

        achievementTransferService.updateById(achievementTransfer);
        // 2. 计算总分值
        String year = null;
        if (achievementTransfer.getTransferYear() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                year = new SimpleDateFormat("yyyy").format(sdf.parse(achievementTransfer.getTransferYear()));
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = achievementTransfer.getTransferYear().substring(0, 4);
            }
        }
        if (year != null) {
            achievementTransferService.updateTotalWorkTransferScore(achievementTransfer.getUserId(), year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }


    @DeleteMapping("/deleteAchieveTrans")
    public ResponseEntity<Map<String, Object>> deleteAchieveTrans(@RequestBody List<Long> ids) {
        // 1. 查出所有要删的数据
        List<AchievementTransfer> toDelete = achievementTransferService.listByIds(ids);

// 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();
        for (AchievementTransfer at : toDelete) {
            if (at.getUserId() != null && at.getTransferYear() != null) {
                String year = null;
                String transferYearStr = at.getTransferYear();
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    Date date;
                    if (transferYearStr.contains("-")) {
                        date = new SimpleDateFormat("yyyy-MM").parse(transferYearStr);
                    } else if (transferYearStr.contains("/")) {
                        date = new SimpleDateFormat("yyyy/MM").parse(transferYearStr);
                    } else {
                        // 直接是 "yyyy"
                        year = transferYearStr;
                        userYearSet.add(at.getUserId() + "#" + year);
                        continue;
                    }
                    year = new SimpleDateFormat("yyyy").format(date);
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = transferYearStr.substring(0, 4);
                }
                userYearSet.add(at.getUserId() + "#" + year);
            }
        }

// 3. 删除
        achievementTransferService.removeByIds(ids);

// 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            achievementTransferService.updateTotalWorkTransferScore(userId, year);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reviewAchieveTransfer")
    public ResponseEntity<Map<String, Object>> reviewAchieveTransfer(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long transferId = Long.valueOf(params.get("transferId").toString());
            String reviewStatus = params.get("reviewStatus").toString(); // 审核通过/审核不通过
            String reviewResult = params.get("reviewResult") != null ? params.get("reviewResult").toString() : "";

            AchievementTransfer transfer = achievementTransferService.getById(transferId);
            if (transfer == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            // 设置审核状态、审核时间、审核说明
            transfer.setTransferReviewStatus(reviewStatus);
            transfer.setTransferReviewTime(java.time.LocalDateTime.now());
            transfer.setTransferReviewResult(reviewResult);

            if ("审核通过".equals(reviewStatus)) {
                transfer.setTransferReviewResult(null); // 审核通过时清空说明
            }
            if ("审核不通过".equals(reviewStatus)) {
                transfer.setTransferStatus("未提交");
            }

            achievementTransferService.updateById(transfer);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportAchievementTransfer(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {


        // 3. 查询 AchievementTransfer（可按年份筛选）
        QueryWrapper<AchievementTransfer> queryWrapper = new QueryWrapper<>();

        if (year != null && !year.isEmpty()) {
            queryWrapper.like("transfer_year", year.substring(0, 4));
        }

        // 只导出审核通过的数据
        queryWrapper.eq("transfer_status", "已提交");

        List<AchievementTransfer> list = achievementTransferService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (AchievementTransfer w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 生成文件名
        String now = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new java.util.Date());
        String fileName = "成果转化-" + now + ".xlsx";

        // 6. 导出
        ExcelExportUtil.export(response, list, AchievementTransfer.class, "成果转化", fileName);
    }
}
